package isn99

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"

	"lottery/models"
	// "github.com/astaxie/beego/logs"
	// "golang.org/x/text/encoding/simplifiedchinese"
	// "golang.org/x/text/transform"
)

var handicapTypeMap map[int]int

func init() {
	handicapTypeMap = make(map[int]int)
	handicapTypeMap[1] = 1
	handicapTypeMap[2] = 2
	handicapTypeMap[4] = 3
	handicapTypeMap[5] = 4
}

func (isn *Isn99) crawlGames() (gameDataResps []*GameDataResp, err error) {
	reqUrl := "http://www.isn99.com/membersite/zh-CN/resource/events/1/1/2/3/0/4/0/1?_=%d"
	reqUrl = fmt.Sprintf(reqUrl, time.Now().Unix())
	req, err := http.NewRequest("GET", reqUrl, nil)
	if err != nil {
		return
	}

	req.Header = isn.getDefaultHeader()
	resp, err := isn.client.Do(req)
	if err != nil {
		return
	}

	data, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return
	}

	// data, _, err = transform.Bytes(simplifiedchinese.GBK.NewDecoder(), data)
	// if err != nil {
	// 	return
	// }

	gameDataResps = make([]*GameDataResp, 0, 2)
	if err = json.Unmarshal(data, &gameDataResps); err != nil {
		return
	}
	return
}

func (isn *Isn99) parseGameData(gameDataResps []*GameDataResp) (games []*models.Game, gameDatas []*models.GameData, err error) {
	if len(gameDataResps) < 1 {
		err = fmt.Errorf("无数据")
		return
	}
	games = make([]*models.Game, 0, 100)
	gameDatas = make([]*models.GameData, 0, 100)
	// for _, gameDataResp := range gameDataResps {
	createTime := time.Now()
	for _, ileague := range gameDataResps[0].Leagues {
		for _, igame := range ileague.Events {
			game := new(models.Game)
			game.LeagueGameName = ileague.Name
			game.LeagueGameId = string(ileague.ID)
			game.PlatformGameId = strconv.Itoa(igame.ID)
			game.PlayTime = time.Unix(igame.StartDate/1000, 0).String()
			game.StartTime = igame.StartDate
			game.HName = igame.Descriptions[0].TeamName
			game.AName = igame.Descriptions[1].TeamName
			games = append(games, game)
			// logs.Debug("%s  %s-%s", ileague.Name, game.HName, game.AName)

			var hscore, ascore int
			fmt.Sscanf(igame.Score, "%d-%d", &hscore, &ascore)
			for i, market := range igame.Markets {
				handicapType, ok := handicapTypeMap[i]
				if !ok {
					continue
				}

				for _, line := range market.Lines {
					if len(line.Selections) < 2 {
						continue
					}

					gameData := new(models.GameData)
					gameData.PlatformGameId = strconv.Itoa(igame.ID)
					gameData.HOrderId = strconv.Itoa(line.Selections[0].ID)
					gameData.AOrderId = strconv.Itoa(line.Selections[1].ID)
					gameData.Handicap = line.Selections[0].Handicap
					gameData.HRate, _ = strconv.ParseFloat(line.Selections[0].OddsFormatted, 64)
					gameData.ARate, _ = strconv.ParseFloat(line.Selections[1].OddsFormatted, 64)
					if line.Selections[0].SelIndicator == "Over" {
						// 大球
						gameData.HIndicator = 1
						gameData.AIndicator = 2
					} else {
						gameData.HIndicator = 2
						gameData.AIndicator = 1
					}
					gameData.HScore = hscore
					gameData.AScore = ascore
					gameData.HandicapType = handicapType
					gameData.AgentId = isn.agentInfo.Id
					gameData.CreateTime = createTime.UnixNano() / int64(time.Millisecond)
					gameDatas = append(gameDatas, gameData)
				}
			}
		}
	}
	// }
	return
}
